package spring.boot.es.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author liuli31
 * @date 2022/3/14
 */
@Configuration
public class GrayScaleElasticConfig {
    private static final Logger log = LoggerFactory.getLogger(GrayScaleElasticConfig.class);

    @Value("${grayscale.elasticsearch.cluster-nodes}")
    private String clusterNodes ;

    @Bean(name = "highLevelClient")
    public RestHighLevelClient  highLevelClient() {
        log.info("GrayScaleFunction es:{}",clusterNodes);
        HttpHost[]  httpHosts = new HttpHost[clusterNodes.split(",").length] ;
        for (int i = 0; i < clusterNodes.split(",").length; i++) {
            String nodes = clusterNodes.split(",")[i];
            String InetSocket [] = nodes.split(":");
            String  host = InetSocket[0];
            Integer  port = Integer.valueOf(InetSocket[1]);
            httpHosts[i]= new HttpHost(host, port);
        }
        RestClientBuilder httpClientBuilder = RestClient.builder(httpHosts);
        return  new RestHighLevelClient(httpClientBuilder);
    }
}
